<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>使用影子 DOM</title>
</head>
<body>
  <script>
    for (const color of ['red', 'green', 'blue']) {
      const div = document.createElement('div');
      const shadowDOM = div.attachShadow({ mode: 'open' });

      document.body.appendChild(div);
      shadowDOM.innerHTML = `
        <p>Make me ${color}</p>

        <style>
          p {
            color: ${color};
          }
        </style>
      `;
    }

    function countP(node) {
      console.log(node.querySelectorAll('p').length);
    }

    countP(document);  // 0

    for (const element of document.querySelectorAll('div')) {
      countP(element.shadowRoot);
    }

    // 1
    // 1
    // 1
  </script>
</body>
</html>